package com.wechat.core.handler;

import cn.hutool.core.util.StrUtil;
import com.wechat.core.constant.Constant;
import com.wechat.core.constant.enums.support.RStatus;
import com.wechat.core.exception.NotLoginException;
import com.wechat.util.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @author： qiujunda
 * @date： 2019/11/24 0:58
 */
@Component
public class TokenUtil {
    @Value("${spring.redis.tokenTimeout}")
    private int timeout;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public LoginBean loginValidate(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
        String token = httpServletRequest.getHeader("token");
        if (StrUtil.isBlank(token)) {
            token = httpServletRequest.getParameter("token");
        }
        if (StrUtil.isBlank(token)) {
            Cookie[] cookies = httpServletRequest.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("token")) {
                        token = cookie.getValue();
                    }
                }
            }
        }

        if (StrUtil.isBlank(token)) {
            throw new NotLoginException("请登录", RStatus.NO_LOGIN);
        }

        Claims claims;
        try {
            claims = jwtTokenUtil.getClaimFromToken(token);
        } catch (JwtException j) {
            throw new NotLoginException("请登录", RStatus.NO_LOGIN);
        }
        String subject = claims.getSubject();
        String openId = claims.getAudience();

        if (StrUtil.isEmpty(subject)) {
            throw new NotLoginException("请登录", RStatus.NO_LOGIN);
        }

        Integer userId = Integer.valueOf(subject);
        if (!redisTemplate.hasKey(Constant.WECHAT_USER_ID + userId)) {
            throw new NotLoginException("请登录", RStatus.NO_LOGIN);
        }
        redisTemplate.expire(Constant.WECHAT_USER_ID + userId, timeout, TimeUnit.SECONDS);
        return LoginBean.builder().openId(openId).token(token).userId(userId).build();
    }
}
